//
//  ListCommunicator.m
//  KoreaFlower
//
//  Created by Nicejinux on 12. 12. 23..
//  Copyright (c) 2012년 Nicejinux. All rights reserved.
//

#import "ListCommunicator.h"
#import <sqlite3.h>

static ListCommunicator *g_sharedInstance = nil;

@implementation ListCommunicator

@synthesize flowerListArray;
@synthesize flowerDic;
@synthesize introReq;
@synthesize indicatorView;
@synthesize indicator;
@synthesize callbackList;

#pragma mark - external interface methods
+ (ListCommunicator *)sharedInstance
{
    if (g_sharedInstance)
        return g_sharedInstance;
    
    @synchronized(self)
    {
        if (!g_sharedInstance)
        {
            g_sharedInstance = [[self alloc] init];
        }
    }
    
    return g_sharedInstance;
}

#pragma mark - internal logic methods
- (id)init
{
    self = [super init];
    if (self)
    {
        callbackList = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (void) requestFlowerList
{
    if (introReq) {
        return;
    }
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@", GET_FLOWER_INFO_JSON];
    introReq = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrl]];
    [introReq setDelegate:self];
    
    [introReq startAsynchronous];
}

- (BOOL)checkData
{
    BOOL canStart = YES;
    
    // DB 에서 데이터 체크. 시작 가능하면 YES, 시작 불가면 NO
    
    return canStart;
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    int responseStatusCode = [request responseStatusCode];
    BOOL isSuccess = (responseStatusCode >= 200 && responseStatusCode < 300) ? YES : NO;
    
    if (isSuccess) {
        flowerDic = [[request responseString] objectFromJSONString];
        NSLog(@"%@", flowerDic);
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[[[flowerDic objectForKey:@"cdnInfo"] objectAtIndex:0] objectForKey:@"cdnPathName"] forKey:@"cdn0"];
        [ud setObject:[[[flowerDic objectForKey:@"cdnInfo"] objectAtIndex:1] objectForKey:@"cdnPathName"] forKey:@"cdn1"];
        [ud synchronize];
        
        [self storeCDNListToDB:flowerDic];
        [self storeFlowerListToDB:flowerDic];
        [self notiSuccessCallBack];
    }
    else
    {

    }
    
    introReq = nil;
}

- (void)notiSuccessCallBack
{
    for (CallBackObjectMethodInfo *callbackInfo in callbackList)
        [callbackInfo.target performSelector:callbackInfo.action withObject:[NSNumber numberWithBool:YES] afterDelay:0];
    
    [callbackList removeAllObjects];
}

- (void)requestFlowerList:(id)target action:(SEL)action isUserInteraction:(BOOL)isUserInteraction
{
    if (target && action)
    {
        CallBackObjectMethodInfo *callbackInfo = [[CallBackObjectMethodInfo alloc] init];
        callbackInfo.target = target;
        callbackInfo.action = action;
        [callbackList addObject:callbackInfo];
    }
    
    [self requestFlowerList];
}

- (BOOL)storeFlowerListToDB:(NSDictionary *)dic
{
    BOOL isSuccess = YES;
    
    //[flowerListDic objectForKey:@"listUpdateTime"];
    //[flowerListDic objectForKey:@"rCode"];
    //[flowerListDic objectForKey:@"rMessage"];
    NSArray *flowerList = [dic objectForKey:@"flowerInfo"];
    
    if (![flowerList count])
    {
        return YES;
    }
    
    sqlite3 *dbObject = [[DBManager sharedInstance] getDatabaseObject];
    
    char* errorMessage;
    sqlite3_exec(dbObject, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
    
    sqlite3_stmt* stmt;
    
    char *sql = DELETE_FlowerInfoList_All;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        NSLog(@"%s failed to sqlite3_step\n%s", __func__, sql);
        sqlite3_finalize(stmt);
        return NO;
    }
    
    sql = INSERT_FlowerInfoList;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    
    NSInteger i = 0;
    NSDictionary *valueIdxDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithInteger:++i], @"flowerNo"      ,
                                 [NSNumber numberWithInteger:++i], @"flowerName"    ,
                                 [NSNumber numberWithInteger:++i], @"categoryOrder" ,
                                 [NSNumber numberWithInteger:++i], @"comment"       ,
                                 [NSNumber numberWithInteger:++i], @"eventYN"       ,
                                 [NSNumber numberWithInteger:++i], @"imgName"       ,
                                 [NSNumber numberWithInteger:++i], @"imgNameSurfix" ,
                                 [NSNumber numberWithInteger:++i], @"subInfo"       ,
                                 [NSNumber numberWithInteger:++i], @"newYN"         ,
                                 [NSNumber numberWithInteger:++i], @"orignPrice"    ,
                                 [NSNumber numberWithInteger:++i], @"salePrice"     ,
                                 [NSNumber numberWithInteger:++i], @"price"         ,
                                 [NSNumber numberWithInteger:++i], @"saleCategoryNo",
                                 [NSNumber numberWithInteger:++i], @"saleCategoryName",
                                 [NSNumber numberWithInteger:++i], @"useCategoryNo" ,
                                 [NSNumber numberWithInteger:++i], @"useCategoryName" ,
                                 [NSNumber numberWithInteger:++i], @"saleYN"        ,
                                 [NSNumber numberWithInteger:++i], @"seasonOnlyYN"  ,
                                 [NSNumber numberWithInteger:++i], @"soldOutYN"     ,
                                 [NSNumber numberWithInteger:++i], @"useYN"         ,
                                 nil];
    
    
    for (NSDictionary *dealItem in flowerList)
    {
        for (NSString *keyString in dealItem)
        {
            NSString *valueObject = [dealItem objectForKey:keyString];
            
            if ([keyString isEqualToString:@"flowerNo"]
                || [keyString isEqualToString:@"categoryOrder"]
                || [keyString isEqualToString:@"orignPrice"]
                || [keyString isEqualToString:@"salePrice"]
                || [keyString isEqualToString:@"price"]
                || [keyString isEqualToString:@"saleCategoryNo"]
                || [keyString isEqualToString:@"useCategoryNo"])
            {
                int value = 0;
                
                if ([valueObject respondsToSelector:@selector(integerValue)])
                {
                    value = [valueObject integerValue];
                }
                
                sqlite3_bind_int(stmt, [[valueIdxDic objectForKey:keyString] intValue], value);
            }
            else
            {
                if ([valueObject isKindOfClass:[NSNull class]])
                {
                    valueObject = @"";
                }
                else if (![valueObject isKindOfClass:[NSString class]])
                {
                    valueObject = [NSString stringWithFormat:@"%@", valueObject];
                }
                
                const char* valueCString = [valueObject UTF8String];
                
                sqlite3_bind_text(stmt, [[valueIdxDic objectForKey:keyString] intValue], valueCString, strlen(valueCString), SQLITE_STATIC);
            }
        }
        
        if (sqlite3_step(stmt) != SQLITE_DONE)
        {
            NSLog(@"%s failed to sqlite3_step\n%@", __func__, dealItem);
            isSuccess = NO;
        }
        
        sqlite3_reset(stmt);
    }
    
    sqlite3_exec(dbObject, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
    sqlite3_finalize(stmt);
    
    NSLog(@"%s completed to store deal list(%d)", __func__, [flowerList count]);
    
    
    return isSuccess;
}

- (BOOL)storeCDNListToDB:(NSDictionary *)dic
{
    BOOL isSuccess = YES;
    
    NSArray *cdnList = [dic objectForKey:@"cdnInfo"];

    if (![cdnList count])
    {
        return YES;
    }
    
    sqlite3 *dbObject = [[DBManager sharedInstance] getDatabaseObject];
    
    char* errorMessage;
    sqlite3_exec(dbObject, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
    
    sqlite3_stmt* stmt;
    
    char *sql = DELETE_CDNInfo_All;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        //        NSLog(@"%s failed to sqlite3_step\n%s", __func__, sql);
        sqlite3_finalize(stmt);
        return NO;
    }
    
    sql = INSERT_CDNInfo;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    
    for (NSDictionary *cdnDic in cdnList)
    {
        NSString *cdnPathNo     = [cdnDic objectForKey:@"cdnPathNo"];
        NSString *cdnPathName   = [cdnDic objectForKey:@"cdnPathName"];
        
        if ([cdnPathNo length] && [cdnPathName length])
        {
            const char* cdnPathNoCString         = [cdnPathNo UTF8String];
            const char* cdnPathNameCString       = [cdnPathName UTF8String];
            
            sqlite3_bind_text(stmt, 1, cdnPathNoCString,         strlen(cdnPathNoCString),        SQLITE_STATIC);
            sqlite3_bind_text(stmt, 2, cdnPathNameCString,       strlen(cdnPathNameCString),      SQLITE_STATIC);
            
            int sqlite2StepResult = sqlite3_step(stmt);
            if (sqlite2StepResult != SQLITE_DONE)
            {
                NSLog(@"%s failed to sqlite3_step - result : %d\n%@", __func__, sqlite2StepResult, cdnDic);
                isSuccess = NO;
            }
            else
            {
                sqlite3_reset(stmt);
            }
        }
    }
    
    sqlite3_exec(dbObject, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
    sqlite3_finalize(stmt);
    
    return isSuccess;
}

- (BOOL)storeSaleCategoryToDB:(NSDictionary *)dic
{
    BOOL isSuccess = YES;
    
    NSArray *categoryList = [dic objectForKey:@"saleCategory"];
    
    if (![categoryList count])
    {
        return YES;
    }
    
    sqlite3 *dbObject = [[DBManager sharedInstance] getDatabaseObject];
    
    char* errorMessage;
    sqlite3_exec(dbObject, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
    
    sqlite3_stmt* stmt;
    
    char *sql = DELETE_SaleCategoryList_All;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        NSLog(@"%s failed to sqlite3_step\n%s", __func__, sql);
        sqlite3_finalize(stmt);
        return NO;
    }
    
    sql = INSERT_SaleCategoryList;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    
    NSInteger i = 0;
    NSDictionary *valueIdxDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithInteger:++i], @"saleCategoryNo",
                                 [NSNumber numberWithInteger:++i], @"saleCategoryOrder",
                                 [NSNumber numberWithInteger:++i], @"saleCategoryName",
                                 [NSNumber numberWithInteger:++i], @"saleCategoryEventYN",
                                 nil];
    
    
    for (NSDictionary *dealItem in categoryList)
    {
        for (NSString *keyString in dealItem)
        {
            NSString *valueObject = [dealItem objectForKey:keyString];
            
            if ([keyString isEqualToString:@"saleCategoryNo"] || [keyString isEqualToString:@"saleCategoryOrder"])
            {
                int value = 0;
                
                if ([valueObject respondsToSelector:@selector(integerValue)])
                {
                    value = [valueObject integerValue];
                }
                
                sqlite3_bind_int(stmt, [[valueIdxDic objectForKey:keyString] intValue], value);
            }
            else
            {
                if ([valueObject isKindOfClass:[NSNull class]])
                {
                    valueObject = @"";
                }
                else if (![valueObject isKindOfClass:[NSString class]])
                {
                    valueObject = [NSString stringWithFormat:@"%@", valueObject];
                }
                
                const char* valueCString = [valueObject UTF8String];
                
                sqlite3_bind_text(stmt, [[valueIdxDic objectForKey:keyString] intValue], valueCString, strlen(valueCString), SQLITE_STATIC);
            }
        }
        
        if (sqlite3_step(stmt) != SQLITE_DONE)
        {
            NSLog(@"%s failed to sqlite3_step\n%@", __func__, dealItem);
            isSuccess = NO;
        }
        
        sqlite3_reset(stmt);
    }
    
    sqlite3_exec(dbObject, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
    sqlite3_finalize(stmt);
    
    NSLog(@"%s completed to store deal list(%d)", __func__, [categoryList count]);
    
    
    return isSuccess;
}

- (BOOL)storeUseCategoryToDB:(NSDictionary *)dic
{
    BOOL isSuccess = YES;
    
    NSArray *categoryList = [dic objectForKey:@"useCategory"];
    
    if (![categoryList count])
    {
        return YES;
    }
    
    sqlite3 *dbObject = [[DBManager sharedInstance] getDatabaseObject];
    
    char* errorMessage;
    sqlite3_exec(dbObject, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
    
    sqlite3_stmt* stmt;
    
    char *sql = DELETE_SaleCategoryList_All;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        NSLog(@"%s failed to sqlite3_step\n%s", __func__, sql);
        sqlite3_finalize(stmt);
        return NO;
    }
    
    sql = INSERT_SaleCategoryList;
    sqlite3_prepare_v2(dbObject, sql, strlen(sql), &stmt, NULL);
    
    NSInteger i = 0;
    NSDictionary *valueIdxDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithInteger:++i], @"useCategoryNo",
                                 [NSNumber numberWithInteger:++i], @"useCategoryOrder",
                                 [NSNumber numberWithInteger:++i], @"useCategoryName",
                                 [NSNumber numberWithInteger:++i], @"useCategoryEventYN",
                                 nil];
    
    
    for (NSDictionary *dealItem in categoryList)
    {
        for (NSString *keyString in dealItem)
        {
            NSString *valueObject = [dealItem objectForKey:keyString];
            
            if ([keyString isEqualToString:@"useCategoryNo"] || [keyString isEqualToString:@"useCategoryOrder"])
            {
                int value = 0;
                
                if ([valueObject respondsToSelector:@selector(integerValue)])
                {
                    value = [valueObject integerValue];
                }
                
                sqlite3_bind_int(stmt, [[valueIdxDic objectForKey:keyString] intValue], value);
            }
            else
            {
                if ([valueObject isKindOfClass:[NSNull class]])
                {
                    valueObject = @"";
                }
                else if (![valueObject isKindOfClass:[NSString class]])
                {
                    valueObject = [NSString stringWithFormat:@"%@", valueObject];
                }
                
                const char* valueCString = [valueObject UTF8String];
                
                sqlite3_bind_text(stmt, [[valueIdxDic objectForKey:keyString] intValue], valueCString, strlen(valueCString), SQLITE_STATIC);
            }
        }
        
        if (sqlite3_step(stmt) != SQLITE_DONE)
        {
            NSLog(@"%s failed to sqlite3_step\n%@", __func__, dealItem);
            isSuccess = NO;
        }
        
        sqlite3_reset(stmt);
    }
    
    sqlite3_exec(dbObject, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
    sqlite3_finalize(stmt);
    
    NSLog(@"%s completed to store deal list(%d)", __func__, [categoryList count]);
    
    
    return isSuccess;
}

@end
